<template>
  <!-- // 分配角色 -->
  <div>
    <el-tree ref="refTree" :data="permissionList" :props="{label:'name'}" default-expand-all :show-checkbox="true" :check-strictly="true" node-key="id" />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hClose">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permisson'
import { tranListToTreeList } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: { curId: { type: String, required: true }},
  data() {
    return {
      permissionList: [],
      permIds: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    async doSave() {
      try {
        const permIds = this.$refs.refTree.getCheckedKeys()
        console.log('permIds', permIds)
        const res = await assignPerm({ id: this.curId, permIds: permIds })
        console.log('分配角色并保存', res)
        this.$emit('success', res.message)
        // 保存数据
      } catch (err) {
        console.log('分配角色并保存', err)
      }
    },
    hSubmit() {
      this.doSave()
    },
    hClose() {
      this.$emit('hPerClose')
    },
    async loadRoleDetail() {
      try {
        const res = await getRoleDetail(this.curId)
        console.log('获取角色权限列表', res)
        this.permIds = res.data.permIds
        // 回填
        this.$refs.refTree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log('获取角色权限列表', err)
      }
    },
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('获取权限列表', res)
        this.permissionList = tranListToTreeList(res.data)
      } catch (err) {
        console.log('获取权限列表', err)
      }
    }
  }
}
</script>
